﻿using crm_data;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace crm_core
{
    public class SqlServerDbContext : DbContext
    {
        public SqlServerDbContext(DbContextOptions<SqlServerDbContext> options)
          : base(options)
        {

        }

        public DbSet<Customer> Customers { get; set; }
        public DbSet<CustomerAddress> CustomerAddresses { get; set; }

        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }
        public DbSet<OrderInvoice> OrderInvoices { get; set; }
        public DbSet<OrderLogistics> OrderLogistics { get; set; }



        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Customer>();
            modelBuilder.Entity<CustomerAddress>()
                .HasOne(ca => ca.Customer)
                .WithMany(c => c.Address)
                .HasForeignKey(ca => ca.CustomerGuid);

            modelBuilder.Entity<Order>();
            modelBuilder.Entity<OrderDetail>()
                .HasOne(od => od.Order)
                .WithMany(o => o.OrderDetails)
                .HasForeignKey(od => od.OrderGuid);

            modelBuilder.Entity<OrderInvoice>()
                .HasOne(oi => oi.Order)
                .WithOne(o => o.OrderInvoice)
                .HasForeignKey<OrderInvoice>(oi => oi.OrderGuid);

            modelBuilder.Entity<OrderLogistics>()
                .HasOne(ol => ol.Order)
                .WithOne(o => o.OrderLogistics)
                .HasForeignKey<OrderLogistics>(ol => ol.OrderGuid);



        }

    }
}
